﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Dataglot;

namespace IrishSettings
{
    public class UpdateApplicationSettings:GenericCommand
    {
        public UpdateApplicationSettings(DataFactory factory, DbConnection shared, DbTransaction transaction):base(factory,shared, transaction)
        {
            ConfigureCommand();
        }

        public UpdateApplicationSettings(DataFactory factory)
            : base(factory)
        {
            ConfigureCommand();
        }

        private void ConfigureCommand()
        {
            const string sql = @"UPDATE [{$ns}_settings_values]
SET serialized_value = @serialized_value 
FROM         {$ns}_settings_applications INNER JOIN
                      {$ns}_settings_schema ON {$ns}_settings_applications.id = {$ns}_settings_schema.application_id INNER JOIN
                      {$ns}_settings_values ON {$ns}_settings_schema.id = {$ns}_settings_values.schema_id
where {$ns}_settings_schema.name = @name 
and {$ns}_settings_applications.application = @application 
and {$ns}_settings_applications.version =  @version 

    ";
            ComposeSql(sql);
            AddParameter("@name", DbType.String);
            AddParameter("@serialized_value", DbType.String);
            AddParameter("@version", DbType.String);
            AddParameter("@application", DbType.String);
            //AddParameter("@user_id", DbType.Int32);
        }

        public void Update(
            string name,
            string serializedValue,
            string application,
            Version version
            )
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentException("Missing setting name", "name");
            if (string.IsNullOrEmpty(application))
                throw new ArgumentException("Missing application name", "application");
            if (version == null)
                throw new ArgumentException("Missing version", "version");
            if (string.IsNullOrEmpty(serializedValue))
            {
                throw new ArgumentException("Serialized Value is missing");
            }
            command.Parameters["@name"].Value = name;
            command.Parameters["@serialized_value"].Value = serializedValue;
            command.Parameters["@version"].Value = version.ToString();
            //command.Parameters["@scope"].Value = scope;
            command.Parameters["@application"].Value = application;
            //command.Parameters["@user_id"].Value = userId;

            int rows = ExecuteNonQuery();
            if (rows == 0)
            {
                throw new InvalidOperationException("Expected 1 row to be affected, but it was 0");
            }
        }
    }
}
